#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>



#include <sys/types.h>         
#include <sys/socket.h>
#include <pthread.h>
#include <signal.h>



#define SPORT 40000
#define SIP "39.100.78.46"
int sockfd=-1;

//封装应用层数据
typedef struct 
{
	unsigned int stu_num;
	char stu_name[50];
	
} data;
void print_err(char *str,int line,int err_no){
	printf("%d,%s:%s\n",line,str,strerror(err_no));
	exit(-1);

}
void signal_fun(int signo){
	if(signo == SIGINT){
		//close(cfd);
		shutdown(sockfd,SHUT_RDWR);
		exit(0);
	}
	printf("signo=%d\n",signo);

}
//次线程接收服务端端数据
void *pth_fun(void *pth_arg){
	int ret=0;
	data stu_data={0};

	while(1){

		bzero(&stu_data,sizeof(stu_data));
		ret=recv(sockfd,&stu_data,sizeof(stu_data),0);
		if(ret ==-1) print_err("receive err:",__LINE__,errno);
		else if(ret>0){
			printf("stu number=%d\n",ntohl(stu_data.stu_num) );
			printf("stu_name=%s\n",stu_data.stu_name) ;
		}
		
	}
	

}




int main(){
	int ret=-1;
	signal(SIGINT,signal_fun);
	//创建使用TCP协议通信的套接字文件
	sockfd=socket(PF_INET,SOCK_STREAM,0);
	if(sockfd ==-1)print_err("socket err:",__LINE__,errno);
	
	struct sockaddr_in seaddr={0};

	seaddr.sin_family=AF_INET;
	seaddr.sin_port=htons(SPORT);
	seaddr.sin_addr.s_addr=inet_addr(SIP);

	ret=connect(sockfd,(struct sockaddr *)&seaddr,sizeof(seaddr));

	if(ret ==-1)print_err("connect err:",__LINE__,errno);

	pthread_t tid;
	//次线程接收用户发送的数据
	ret=pthread_create(&tid,NULL,pth_fun,NULL);
	if(ret ==-1)print_err("pthread_create err:",__LINE__,errno);

	data stu_data ={0};
	int tmp_num=0;
	while(1){
		bzero(&stu_data,sizeof(stu_data));
		printf("input stu_num:\n");
		scanf("%d",&tmp_num);
		stu_data.stu_num=htonl(tmp_num);

		//char的数据不需要进行端序转换
		printf("input stu_name\n");
		scanf("%s",stu_data.stu_name);

		ret=send(sockfd,(void *) &stu_data,sizeof(stu_data),0);
		if(ret ==-1) print_err("send err:",__LINE__,errno);

	}


	return 0;
}



